package com.mes.bac.backend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mes.bac.backend.entity.SystemConfig;
import com.mes.bac.backend.mapper.SystemConfigMapper;
import com.mes.bac.backend.service.ISystemConfigService;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SystemConfigServiceImpl extends ServiceImpl<SystemConfigMapper, SystemConfig> implements ISystemConfigService {

    // 使用ConcurrentHashMap保证线程安全
    private final Map<String, String> configCache = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        refreshConfigCache();
    }

    @Override
    public String getConfigValue(String key) {
        return configCache.get(key);
    }

    @Override
    public void refreshConfigCache() {
        List<SystemConfig> configs = this.list();
        Map<String, String> newCache = configs.stream()
                .collect(Collectors.toMap(SystemConfig::getConfigKey, SystemConfig::getConfigValue));
        configCache.clear();
        configCache.putAll(newCache);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateConfigs(List<SystemConfig> configs) {
        // 使用MyBatis-Plus的批量更新/保存功能
        this.saveOrUpdateBatch(configs);
        // 更新数据库后，立即刷新内存缓存
        refreshConfigCache();
    }
}